package com.cangshi.controller;

import com.cangshi.entity.Activity;
import com.cangshi.entity.JsonObject;
import com.cangshi.entity.UserBaseInfo;
import com.cangshi.exception.JSONException;
import com.cangshi.service.ActivityService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created by Eoly on 2017/4/26.
 */
@Controller
@ResponseBody
@RequestMapping("/")
public class ActivityController {

    @Autowired
    ActivityService activityService;

    @RequestMapping(value = "user/activity/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public JsonObject addActivity(@Valid @RequestBody Activity activity, BindingResult result, HttpServletRequest request) {

        if (result.hasErrors()) {
            // 解析错误
            StringBuilder stringBuilder = new StringBuilder();
            for (ObjectError error : result.getAllErrors()) {
                stringBuilder.append(error.getDefaultMessage()).append(". ");
            }
            throw new JSONException(191, stringBuilder.toString());
        }

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        return activityService.addActivity(activity, userLogin);
    }

    @RequestMapping(value = "/activities/page/{page}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findActivities(@PathVariable Integer page) {
        JsonObject<PageInfo> jsonObject = new JsonObject<PageInfo>();
        PageInfo<Activity> pageInfo = activityService.findActivitiesSimply(page);
        if (pageInfo.getList().size() == 0) {
            jsonObject.setError(291);
            jsonObject.setMes("该页的活动信息为空");
        } else {
            jsonObject.setError(0);
            jsonObject.setMes("获取成功，共有" + pageInfo.getPages() + "页，当前是第" + pageInfo.getPageNum() + "页");
        }
        jsonObject.setData(pageInfo);
        return jsonObject;
    }

    @RequestMapping(value = "/activities/{activityId}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findActivity(@PathVariable Integer activityId) {
        JsonObject<Activity> jsonObject = new JsonObject<Activity>();
        jsonObject.setData(activityService.findActivityByActivityId(activityId));
        jsonObject.setError(0);
        jsonObject.setMes("获取成功");
        return jsonObject;
    }
}
